import requests
from dashscope import Generation
import dashscope


# 设置 API Keys
dashscope.api_key = ""  # 替换为你自己的 DashScope API Key
SENIVERSE_KEY = ""  # 替换为你自己的心知天气 Key
AMAP_KEY = ""  # 替换为你自己的高德地图 Key

# API 地址
WEATHER_API_URL = "https://api.seniverse.com/v3/weather/now.json"
GEOCODING_API_URL = "https://restapi.amap.com/v3/geocode/geo"


# 获取城市名
def get_city_name(address):
    params = {
        "address": address,
        "key": AMAP_KEY
    }
    try:
        response = requests.get(GEOCODING_API_URL, params=params, timeout=10).json()
        if response.get("status") == "1" and len(response.get("geocodes", [])) > 0:
            city = response["geocodes"][0]["city"]
            return city
        else:
            print("地址解析失败：", response)
            return None
    except Exception as e:
        print("获取城市名异常：", e)
        return None


# 获取天气信息
def get_weather(city):
    params = {
        "location": city,
        "key": SENIVERSE_KEY,
        "language": "zh-Hans",
        "unit": "c"
    }

    try:
        url = WEATHER_API_URL + "?" + "&".join([f"{k}={v}" for k, v in params.items()])
        print("请求天气的完整URL：", url)

        response = requests.get(WEATHER_API_URL, params=params, timeout=10).json()

        if "results" in response and len(response["results"]) > 0:
            result = response["results"][0]
            now = result.get("now", {})
            return {
                "temp": now.get("temperature"),
                "feelsLike": now.get("feels_like", now.get("temperature")),
                "text": now.get("text"),
                "windDir": now.get("wind_direction"),
                "windScale": now.get("wind_scale")
            }
        else:
            print("天气接口返回异常：", response)
            return None
    except requests.exceptions.RequestException as e:
        print("网络请求异常：", e)
        return None


# 使用 Qwen 生成自然语言回复
def ai_response(prompt):
    generation = Generation()
    try:
        response = generation.call(
            model="qwen-plus",  # 可选 qwen-max / qwen-plus / qwen-turbo
            prompt=prompt
        )
        return response.output.text
    except Exception as e:
        print("AI 调用失败：", e)
        return "抱歉，我现在无法提供智能建议。请稍后再试。"


# 构建提示词（Prompt）
def build_prompt(weather_info, user_query):
    return f"""
你是一个智能助手，可以根据天气信息提供自然语言建议。

当前天气信息如下：
- 温度：{weather_info['temp']}℃
- 体感温度：{weather_info['feelsLike']}℃
- 天气状况：{weather_info['text']}
- 风向：{weather_info['windDir']}
- 风力等级：{weather_info['windScale']}级

用户的问题是："{user_query}"

请根据天气信息和用户问题，用中文给出简洁、实用的建议。
"""


# 主程序（AI Agent）
def ai_weather_agent():
    address = input("📍 请输入城市或地址：")
    print("正在获取城市名...")
    city = get_city_name(address)
    if not city:
        print("无法获取城市名。")
        return

    print(f"正在获取天气信息（城市名：{city}）...")
    weather = get_weather(city)
    if not weather:
        print("无法获取天气信息。")
        return

    print("\n当前天气信息：")
    print(f"温度：{weather['temp']}℃")
    print(f"体感温度：{weather['feelsLike']}℃")
    print(f"天气：{weather['text']}")
    print(f"风向：{weather['windDir']}，风力等级：{weather['windScale']}级")

    while True:
        user_query = input("\n🤖 有什么我可以帮您？（输入“退出”结束）：")
        if user_query == "退出":
            print("再见！欢迎下次使用！")
            break

        prompt = build_prompt(weather, user_query)
        answer = ai_response(prompt)
        print("\n回答：")
        print(answer)


# 启动 AI Agent
if __name__ == "__main__":
    ai_weather_agent()